package lib

import (
	"errors"
	"github.com/golang-jwt/jwt"
	"time"
)

const (
	JwtContextKey     = "auth"
	UserNameClaimsKey = "name"
	UserIdClaimsKey   = "id"
	ExpClaimsKey      = "exp"
)

type Token struct {
	UserName string
	UserId   uint64
}

type TokenOptions struct {
	ExpireTime time.Duration
	Secret     string
}

func JwtAuth(h Token, options *TokenOptions) (t string, err error) {
	token := jwt.New(jwt.SigningMethodHS256)
	claims := token.Claims.(jwt.MapClaims)
	claims[UserNameClaimsKey] = h.UserName
	claims[UserIdClaimsKey] = h.UserId
	claims[ExpClaimsKey] = time.Now().Add(options.ExpireTime).Unix()
	t, err = token.SignedString([]byte(options.Secret))
	if err != nil {
		return "", errors.New("JWT Generate Failure")
	}
	return t, nil
}

func JwtParse(c *GinContext) *Token {
	value, exists := c.Get(JwtContextKey)
	if !exists {
		return nil
	}
	user := value.(*jwt.Token)
	claims := user.Claims.(jwt.MapClaims)
	return &Token{
		UserName: claims[UserNameClaimsKey].(string),
		UserId:   uint64(claims[UserIdClaimsKey].(float64)),
	}
}
